import { refreshApi } from '@/api/job'
import { useUserStore } from '@/stores/user'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { useLoadingStore } from '@/stores/loading'

export const baseURL = 'http://127.0.0.1:3007'

const request = axios.create({
  baseURL,
  timeout: 15000
})
// 请求拦截器
request.interceptors.request.use(
  (config) => {
    const store = useUserStore()
    const loadingStore = useLoadingStore()

    loadingStore.showLoading()

    if (store.token && config.headers) {
      config.headers['Authorization'] = store.token
    }
    return config
  },
  (err) => {
    const loadingStore = useLoadingStore()
    loadingStore.hideLoading()
    return Promise.reject(err)
  }
)
// 响应拦截器
request.interceptors.response.use(
  (res) => {
    const loadingStore = useLoadingStore()
    loadingStore.hideLoading()
    return res.data
  },
  async (err) => {
    const store = useUserStore()
    const router = useRouter()
    const loadingStore = useLoadingStore()

    loadingStore.hideLoading()

    // 如果是401错误且有refresh token,尝试刷新token
    if (err.response.status === 401 && store.refreshToken) {
      try {
        // 刷新token
        const res = await refreshApi({
          refreshToken: store.refreshToken
        })
        // 更新store中的token
        store.updateToken(res.token, res.refreshToken)

        // 重试失败的请求
        const config = err.config
        config.headers['Authorization'] = res.token

        return request(config)
      } catch (refreshError) {
        // refresh token也过期,清除用户信息并跳转登录
        store.clearUserInfo()
        router?.push({
          path: '/login',
          query: { returnUrl: router.currentRoute.value.fullPath }
        })
        return Promise.reject(refreshError)
      }
    }

    // 其他错误直接reject
    return Promise.reject(err)
  }
)
export default request
